<?php
/**
 * FacebookConnect class file.
 * @author Christoffer Niska <ChristofferNiska@gmail.com>
 * @copyright Copyright &copy; Christoffer Niska 2011-
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 */

require(dirname(__FILE__) . '/../../vendors/facebook/facebook.php'); // Yii::import() will not work in this case

/**
 * Facebook connection application component.
 */
class FacebookConnect extends CApplicationComponent
{
	/**
	 * @property string Facebook application id.
	 */
	public $appId;
	/**
	 * @property string Facebook application secret.
	 */
	public $appSecret;
	/**
	 * @property boolean whether file uploads are enabled.
	 */
	public $fileUpload;
	/**
	 * @property integer the Facebook user id.
	 */
	protected $_userId;
	/**
	 * @property Facebook the Facebook application instance.
	 */
	protected $_facebook;

	/**
	 * Initializes this component.
	 */
	public function init()
	{
		$config = array(
			'appId' => $this->appId,
			'secret' => $this->appSecret
		);

		if ($this->fileUpload !== null)
			$config['fileUpload'] = $this->fileUpload;

		$this->_facebook = new Facebook($config);
	}

	/**
	 * Logs in the current user using facebook.
	 * @return boolean whether the user was logged in successfully
	 */
	public function login()
	{
		$user = $this->loadUser();

		if ($user === null)
		{
			$profile = $this->getData('me'); // get data for the logged in user

			if (!empty($profile))
			{
				$user = new User();
				$user->name = $profile['username'];
				$user->fbuid = $profile['id'];
				$user->save(false);
			}
		}

		if ($user !== null)
		{
			// NOTE: Facebook users are not authenticated using a password
			// so we can simply generate a random one to prevent misuse.
			$identity = new UserIdentity($user->name, uniqid(rand(),true));
			$identity->authenticate(UserIdentity::AUTH_TYPE_FACEBOOK);

			if ($identity->errorCode === UserIdentity::ERROR_NONE)
			{
				$duration = 3600 * 24 * 30; // 30 days
				Yii::app()->user->login($identity, $duration);
				return true;
			}
		}

		return false;
	}
	
	/**
	 * Returns the model for the currently logged in Facebook user.
	 * @return User the user model.
	 */
	public function loadUser()
	{
		$fbuid = $this->getUserId();
		return $fbuid > 0 ? User::model()->findByAttributes(array('fbuid'=>$this->getUserId())) : null;
	}

	/**
	 * Returns data from the API for a specific id.
	 * @param integer $id the facebook id.
	 * @return array the Facebook user profile.
	 */
	public function getData($id)
	{
		$data = array();

		try
		{
			$data = $this->_facebook->api('/'.$id);
		}
		catch (FacebookApiException $e)
		{
			//Yii::app()->user->logout();
		}

		return $data;
	}

	/**
	 * @return integer the Facebook user id.
	 */
	public function getUserId()
	{
		if ($this->_userId !== null)
			return $this->_userId;
		else
		{
			$userId = 0;

			try
			{
				$userId = $this->_facebook->getUser();
			}
			catch (FacebookApiException $e)
			{
				//Yii::app()->user->logout();
			}

			return $this->_userId = $userId;
		}
	}

	/**
	 * @return Facebook the Facebook application instance.
	 */
	public function getFacebook()
	{
		return $this->_facebook;
	}
}
